// 事件系统 - 负责模块间的通信
export class EventSystem {
    private listeners: Map<string, Array<{ callback: Function, target: any }>> = new Map();
    
    // 注册事件监听
    public on(eventName: string, callback: Function, target: any): void {
        if (!this.listeners.has(eventName)) {
            this.listeners.set(eventName, []);
        }
        
        const eventListeners = this.listeners.get(eventName);
        eventListeners.push({ callback, target });
    }
    
    // 取消事件监听
    public off(eventName: string, callback: Function, target: any): void {
        if (!this.listeners.has(eventName)) return;
        
        const eventListeners = this.listeners.get(eventName);
        const index = eventListeners.findIndex(listener => 
            listener.callback === callback && listener.target === target
        );
        
        if (index !== -1) {
            eventListeners.splice(index, 1);
        }
    }
    
    // 取消目标的所有事件监听
    public offTarget(target: any): void {
        this.listeners.forEach((listeners, eventName) => {
            const newListeners = listeners.filter(listener => listener.target !== target);
            this.listeners.set(eventName, newListeners);
        });
    }
    
    // 触发事件
    public emit(eventName: string, ...args: any[]): void {
        if (!this.listeners.has(eventName)) return;
        
        const eventListeners = this.listeners.get(eventName).slice();
        for (const listener of eventListeners) {
            listener.callback.apply(listener.target, args);
        }
    }
    
    // 清空所有事件监听
    public clear(): void {
        this.listeners.clear();
    }
}